<template>
  <div class="app-container" >
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类" prop="categorizeCode">
        <el-cascader  v-model="categorizeCodeArr" style="width: 500px" @change="changeCategorizeCode"
                      :options="$store.state.factorDict.categorizeTreeDict"
                      :props="{value:'id',label:'chineseName',children:'children',checkStrictly:true,}"
                      clearable></el-cascader>
      </el-form-item>
<!--      <el-form-item label="产品ID" prop="productId">-->
<!--        {{queryParams.productId}}-->
<!--      </el-form-item>-->
<!--      <el-form-item label="阶段ID" prop="stageId">-->
<!--        {{queryParams.stageId}}-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini"
          @click="handleAdd" >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete"  size="mini"
          :disabled="multiple" @click="handleDelete" >删除</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productConsumablesList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50" />
<!--      <el-table-column label="产品ID" align="center" prop="productId" />-->
        <el-table-column label="环节" align="center" prop="categorizeCode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
         <span v-if="scope.row.categorizeCode">
           {{selectDictLabel(stageOptions, scope.row.stageId,'id','name')}}
         </span>
            </template>
        </el-table-column>
      <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true"/>
      <el-table-column label="分类" align="center" prop="categorizeCode" width="500" :show-overflow-tooltip="true">
        <template slot-scope="scope">
         <span v-if="scope.row.categorizeCode">
           {{selectDictLabels($store.state.factorDict.categorizeInfoOptions, scope.row.categorizeCode,',','id','chineseName')}}
         </span>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="quantity" width="80" :show-overflow-tooltip="true"/>
      <el-table-column label="系数" align="center" prop="factorNum"  width="80" :show-overflow-tooltip="true"/>
      <el-table-column label="单位" align="center" prop="factorUnit" :show-overflow-tooltip="true"/>
      <el-table-column label="上下游" align="center" prop="status" width="80" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{selectDictLabelDefault($store.state.factorDict.factorTypeOptions, scope.row.factorType)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品耗材对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px"  append-to-body :close-on-click-modal="false" custom-class="dialogPadDiv">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="产品ID" prop="productId">-->
<!--          <el-input v-model="form.productId" placeholder="请输入产品ID" />-->
<!--        </el-form-item>-->
        <el-form-item label="环节" prop="stageId">
            <el-select v-model="form.stageId" placeholder="请选择环节" style="width: 100%">
                <el-option v-for="dict in stageOptions"
                           :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="分类" prop="categorizeCode">
          <el-cascader  v-model="categorizeCodeArr" style="width: 100%" @change="chickCategorizeCode"
                        :options="$store.state.factorDict.categorizeTreeDict1"
                        :props="{value:'idStr',label:'chineseName',children:'children'}"/>
        </el-form-item>
        <el-form-item label="排放因子" prop="factorNum" v-if="form.id==null">
          <el-select v-model="form.checkFactor" placeholder="选择排放因子" style="width: 100%" @change="checkFactorFun">
            <el-option v-for="dict in factorItemList" :key="dict['emissions']"
                       :label="dict['emissions']+'【'+dict['unit']+'】'+(dict['type']==1?'上':'下')"
                       :value="dict['emissions']+'_'+dict['type']" />
          </el-select>
        </el-form-item>
        <el-form-item label="排放因子" prop="factorNum">
          <el-input v-model="form.factorNum" placeholder="请输入排放因子" style="width: 60%"/>
          <el-input v-model="form.factorUnit" placeholder="排放单位" style="width: 40%"/>
          <el-form-item label="" prop="factorUnit"/>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="上下游" prop="factorType">
          <el-select v-model="form.factorType" placeholder="请选择上下游" style="width: 100%">
            <el-option v-for="dict in $store.state.factorDict.factorTypeOptions"
                       :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProductConsumables, getProductConsumables, delProductConsumables, addProductConsumables, updateProductConsumables, exportProductConsumables } from "@/api/factor/productConsumables";

export default {
  name: "ProductConsumables",
  data() {
    return {
      categorizeCodeArr: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品耗材表格数据
      factorItemList: [],
      productConsumablesList: [],
        stageOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: 0,
        stageId: null,
          stageIds: [],
        categorizeCode: null,
        quantity: null,
        name: null,
        factorNum: null,
        factorUnit: null,
        factorType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {

  },
  methods: {
    checkFactorFun(val){
      for (let item of this.factorItemList){
        if((item['emissions']+'_'+item['type'])===val){
            this.form.factorNum = item['emissions'];
            this.form.factorUnit = item['unit'];
            this.form.factorType = item['type'];
          return
        }
      }
      this.form.factorNum = null;
      this.form.factorUnit = null;
      this.form.factorType = null;

    },
    changeCategorizeCode(list){
      this.queryParams.categorizeCode = list.join(",");
      if(list.length<3){
        this.queryParams.categorizeCode =this.queryParams.categorizeCode+",";
      }
    },
    chickCategorizeCode(list){
       for (let item of this.$store.state.factorDict.categorizeInfoOptions){
         if(item.idStr===list[list.length-1]){
           if(item.factorItemList&&item.factorItemList.length>0){
             this.factorItemList=item.factorItemList
           }else {
             this.factorItemList=[];
           }
           return
         }
       }
      this.factorItemList=[];
    },
    checkStageItem(item){
      this.queryParams.productId=item.productId;
      let stageIds = [item.id];
      let stageOptions = [];
      if(item.type==2){
          stageOptions.push(item);
      }
        if(item.children){
            for (let menu of  item.children){
                stageIds.push(menu.id);
                if(menu.type==2){
                    stageOptions.push(menu);
                }
            }
        }
      this.queryParams.stageIds=stageIds;
      this.stageOptions=stageOptions;
      this.getList();
    },
    /** 查询产品耗材列表 */
    getList() {
      this.loading = true;
      listProductConsumables(this.queryParams).then(response => {
        this.productConsumablesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productId: this.queryParams.productId,
        stageId: null,
        categorizeCode: null,
        quantity: null,
        name: null,
        factorNum: null,
        factorUnit: null,
        checkFactor: null,
        factorType: null
      };
      this.resetForm("form");
      this.categorizeCodeArr=[];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if(this.stageOptions.length>0){
          this.form.stageId = this.stageOptions[0].id;
      }
      this.open = true;
      this.title = "添加产品排放";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getProductConsumables(row.id).then(response => {
        this.form = response.data;
        if(response.data.categorizeCode){
          this.categorizeCodeArr = response.data.categorizeCode.split(",");
        }
        this.open = true;
        this.title = "修改产品排放";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if(this.categorizeCodeArr.length>0){
        this.form.categorizeCode = this.categorizeCodeArr.join(",");
      }else {
        this.form.categorizeCode = '';
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProductConsumables(this.form).then(response => {
              if (response.code === '200') {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addProductConsumables(this.form).then(response => {
              if (response.code === '200') {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除产品耗材编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProductConsumables(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有产品耗材数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportProductConsumables(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
